package main

import (
	"fmt"
	//"strings"
	"context"
	MSG "feishup2pclient/msg"
	"sync/atomic"

	"github.com/ccding/go-stun/stun"
	//"github.com/wailsapp/wails/v2/pkg/runtime"
	//"github.com/wailsapp/wails/v2"
)

const (
	DefaultStunAddr = "stun.qq.com"
	DefaultStunPort = "3478"
)

var (
	StunAddr = DefaultStunAddr
	StunPort = DefaultStunPort
)
var (
	AppCtx = context.Background()
)

type NatPage struct {
	ctx  context.Context
	flag int32
	Num  int32
}

func NewNatPage() *NatPage {
	return &NatPage{}
}

func (np *NatPage) startup(ctx context.Context) {
	np.ctx = ctx
	np.Num = 100
}

//设置IP地址
func (np *NatPage) NTP_Set_addr(addr string) string {
	StunAddr = addr
	updateOrAddKey("StunAddr", StunAddr)
	return "ok"
}

//获取IP 地址
func (np *NatPage) NTP_Get_addr() string {

	return StunAddr
}

//设置端口号
func (np *NatPage) NTP_Set_port(port string) string {
	StunPort = port
	updateOrAddKey("StunPort", StunPort)
	return "ok"
}

//获得端口号
func (np *NatPage) NTP_Get_port() string {
	return StunPort
}

//获取ntp 状态
func (np *NatPage) NTP_checking() string {
	if !atomic.CompareAndSwapInt32(&np.flag, 0, 1) {
		return "checking..."
	}
	go func(np *NatPage) {
		defer func() {
			atomic.StoreInt32(&np.flag, 0)
		}()

		ser := StunAddr
		port := StunPort

		if ser == "" {
			//	runtime.EventsEmit(AppCtx, "nat", "NAT服务器地址不能为空")
			MSG.NatCheck("NAT服务器地址不能为空")
			return
		}

		if port == "" {
			//	runtime.EventsEmit(AppCtx, "nat", "NAT服务器端口不能为空")
			MSG.NatCheck("NAT服务器端口不能为空")
			return
		}

		serverAddr := fmt.Sprintf("%s:%s", ser, port)

		client := stun.NewClient()
		client.SetServerAddr(serverAddr)
		println(np.Num, serverAddr)
		nat, host, err := client.Discover()
		println(np.Num)
		if err != nil {
			//	runtime.EventsEmit(AppCtx, "nat", fmt.Sprintf("NAT  ERR %v", err.Error()))
			MSG.NatCheck(fmt.Sprintf("NAT  ERR %v", err.Error()))
			return
		}
		println(np.Num)
		if host == nil {
			//	runtime.EventsEmit(AppCtx, "nat", "NAT-host获取失败")
			MSG.NatCheck("NAT-host获取失败")
			return
		}
		println(np.Num)
		//	runtime.EventsEmit(AppCtx, "nat", "阿这")
		println(np.Num)
		MSG.NatCheck(fmt.Sprintf("Nat类型:  %s;  外网IP:  %s:%d", nat, host.IP(), host.Port()))
		println(np.Num)
	}(np)
	return "NAT 开始检测"
}
